﻿using System;
using System.IO;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using Jade.Tools.SL.Windows.Extensions;
using JulMar.Silverlight.Interfaces;
using JulMar.Silverlight.Mvvm;
using JulMar.Siverlight.Helpers.Interactivity;
using MediaBrowserSL.RIA.MediaBrowserServiceReference;
using MediaBrowserSL.RIA.MvvmUtils;
using MediaBrowserSL.RIA.MvvmUtils.UI;
using MediaBrowserSL.RIA.Services;
using MediaBrowserSL.RIA.Tools;
using System.ServiceModel;

namespace MediaBrowserSL.RIA.ViewModels
{
    public class ManageMoviesViewModel : ViewModelBase
    {
        #region Private Member

        private IMediaRiaServices service;
        private Media newMedia;
        private FileInfo selectedFileMovie;
        private FileInfo selectedImageMovie;
        private BitmapImage selectedBitmapImageMovie;
        private IErrorVisualizer errorVisualizer;
        private bool isSaving;
        private bool isAddingMovie;
        private ICustomMessageBoxVisualizer customMessageBoxVisualizer;

        #endregion

        #region Public Member

        public Media NewMedia
        {
            get
            {
                return newMedia;
            }
            set
            {

                newMedia = value;
                OnPropertyChanged("NewMedia");
            }
        }

        public FileInfo SelectedFileMovie
        {
            get { return selectedFileMovie; }
            set
            {
                selectedFileMovie = value;
                OnPropertyChanged("SelectedFileMovie");
                NewMedia.UrlContent = selectedFileMovie.ToString();
            }
        }

        public FileInfo SelectedImageMovie
        {
            get { return selectedImageMovie; }
            set
            {
                selectedImageMovie = value;
                OnPropertyChanged("SelectedImageMovie");
                NewMedia.UrlImage = selectedImageMovie.ToString();

                //selected Bitmap Image Movie
                Stream stream = selectedImageMovie.OpenRead();
                SelectedBitmapImageMovie = new BitmapImage();
                SelectedBitmapImageMovie.SetSource(stream);
            }
        }

        public bool IsAddingMovie
        {
            get { return isAddingMovie; }
            set
            {
                isAddingMovie = value;
                OnPropertyChanged("IsAddingMovie");
            }
        }

        public BitmapImage SelectedBitmapImageMovie
        {
            get { return selectedBitmapImageMovie; }
            set
            {
                selectedBitmapImageMovie = value;
                OnPropertyChanged("SelectedBitmapImageMovie");
            }
        }

        public bool IsSaving
        {
            get
            {
                return isSaving;
            }
            set
            {

                isSaving = value;
                OnPropertyChanged("IsSaving");
                RaiseCanExecuteChanged();
            }
        }

        #endregion

        #region Command
        public DelegatingCommand SaveMovieCommand
        {
            get;
            private set;
        }

        public ICommand DropPictureCommand
        {
            get;
            private set;
        }

        #endregion

        #region Ctor
        public ManageMoviesViewModel(IMediaRiaServices service)
        {
            this.service = service;

            SaveMovieCommand = new DelegatingCommand(SaveMovie, CanSaveMovie);
            DropPictureCommand = new DelegatingCommand<EventInformation>(DropPicture);

            errorVisualizer = Resolve<IErrorVisualizer>();
            customMessageBoxVisualizer = Resolve<ICustomMessageBoxVisualizer>();

            //Init Mediator
            RegisterWithMessageMediator();
        }

        #endregion

        #region Private Methods

        /// <summary>
        /// Save Movie and Upload File
        /// </summary>
        private void SaveMovie()
        {
            IsSaving = true;
            //Create Media
            if (NewMedia.Id == 0)
            {
                NewMedia.CreationDate = DateTime.Now;
                service.CreateMedia(OnMovieCreated, NewMedia, SessionMb.CurrentUser, SelectedImageMovie, SelectedFileMovie);
            }
            //Update Media
            else
            {
                service.UpdateMedia(OnMovieUpdated, NewMedia);
            }
        }

        /// <summary>
        /// On Movie Created
        /// </summary>
        /// <param name="Media"></param>
        /// <param name="ex"></param>
        private void OnMovieCreated(Media m, Exception ex)
        {
            IsSaving = false;
            if (ex == null)
            {
                SendMessage(MediatorMessages.AddMovieToList, m);
                CloseCommand.Execute(null);
            }
            else if (ex.GetType().Equals(typeof(FullServerException)))
            {
                if (customMessageBoxVisualizer != null)
                {
                    customMessageBoxVisualizer.Show(null,
                                                        "Votre espace serveur est plein !",
                                                        "Espace indisponible",
                                                        MessageBoxButton.OK,
                                                        MessageBoxImage.Error);
                }

            }
            else
            {
                if (customMessageBoxVisualizer != null)
                {
                    customMessageBoxVisualizer.Show(null, ((FaultException<ErrorDataContract>)ex).Detail.Detail, ex.Message, MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        /// <summary>
        /// On Movie Updated
        /// </summary>
        /// <param name="ex"></param>
        private void OnMovieUpdated(Exception ex)
        {
            IsSaving = false;
            if (ex == null)
            {
                SendMessage(MediatorMessages.UpdateMovieToList, NewMedia);
                CloseCommand.Execute(null);
            }
            else
            {
                if (customMessageBoxVisualizer != null)
                {
                    customMessageBoxVisualizer.Show(null, ((FaultException<ErrorDataContract>)ex).Detail.Detail, ex.Message, MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        /// <summary>
        /// Can Save Movie
        /// </summary>
        /// <returns></returns>
        private bool CanSaveMovie()
        {
            bool result = false;

            if (!IsSaving)
            {
                result = NewMedia.ValidData() && !String.IsNullOrEmpty(NewMedia.UrlContent) && !String.IsNullOrEmpty(NewMedia.UrlImage);
            }

            return result;
        }

        /// <summary>
        /// Drop Picture
        /// </summary>
        /// <param name="e"></param>
        private void DropPicture(EventInformation e)
        {
            DragEventArgs de = e.EventParameter as DragEventArgs;

            if ((de.Data != null) && (de.Data.GetDataPresent(DataFormats.FileDrop)))
            {
                FileInfo[] files = de.Data.GetData(DataFormats.FileDrop) as FileInfo[];

                if (files != null)
                {
                    FileInfo f = files[0];
                    if (f.Name.IsImageFile())
                    {
                        SelectedImageMovie = f;
                    }
                }
            }
        }

        /// <summary>
        /// New Media Property Changed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void NewMedia_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            RaiseCanExecuteChanged();
        }

        /// <summary>
        /// Raise can execute
        /// </summary>
        private void RaiseCanExecuteChanged()
        {
            SaveMovieCommand.RaiseCanExecuteChanged();
        }

        #endregion

        #region Public Methods
        /// <summary>
        /// LogOut
        /// </summary>
        [MessageMediatorTarget(MediatorMessages.EditMovie)]
        public void EditMovie(Media media)
        {
            NewMedia = media.Clone();
            NewMedia.Category = new Category() { Id = 1 };
            NewMedia.UrlContent = Path.GetFileName(media.UrlContent);

            IsAddingMovie = (NewMedia.Id == 0) ? true : false;

            if (NewMedia.UrlImage != null)
            {
                Uri uri = new Uri(NewMedia.UrlImage, UriKind.RelativeOrAbsolute);
                SelectedBitmapImageMovie = new BitmapImage(uri);
            }
            else
            {
                Uri uri = new Uri("/MediaBrowserSL.RIA;component/Images/DragDrop.png", UriKind.Relative);
                SelectedBitmapImageMovie = new BitmapImage(uri);
            }

            NewMedia.PropertyChanged += NewMedia_PropertyChanged;
        }
        #endregion
    }
}
